/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.yuanma.android.boan;

import android.app.IntentService;
import android.content.ContentValues;
import android.content.Intent;
import android.content.Context;
import android.content.SharedPreferences;

//import org.apache.http.HttpStatus;

import java.io.*;
import org.json.*;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Vector;

import android.net.Uri;
import android.app.Notification;
import android.app.TaskStackBuilder;
//import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.support.v4.app.NotificationCompat;
//import android.support.v4.app.NotificationManagerCompat;

import android.util.Log;

public class JsonPullService extends IntentService {

    static Vector<Message> msgsToRead=new Vector<Message>(10);
    static Vector<Message> msgsToReview=new Vector<Message>(10);
    public static int max_id=0;
    public static boolean running=false;
    static public String loginName="";
    static public String userName="";

    // Used to write to the system log from this class.
    public static final String LOG_TAG = "JsonPullService";

    // Defines and instantiates an object for handling status updates.
    private BroadcastNotifier mBroadcaster;
    private boolean appRunning;
    private static int readHintCount=3;
    
    /**
     * An IntentService must always have a constructor that calls the super constructor. The
     * string supplied to the super constructor is used to give a name to the IntentService's
     * background thread.
     */
    public JsonPullService() {

        super("JsonPullService");
	
	try{
	    
	    mBroadcaster = new BroadcastNotifier(this);
	    appRunning=true;
	}catch(Exception ee)
	    {
		appRunning=false;
	    }
	
	
    }
    private final String paraFileName="yuanma._boan_param";
    
    private void saveUserInfo()
    {
	SharedPreferences sharedPref = getSharedPreferences(paraFileName,Context.MODE_PRIVATE);
	SharedPreferences.Editor editor = sharedPref.edit();
	editor.putString(getString(R.string.login_name_key), LoginActivity.loginName);
	editor.putString(getString(R.string.user_name_key), LoginActivity.userName);
	editor.commit();
    }
    
    private  void fetchLocalUserInfo()
    {
	
	SharedPreferences sharedPref = getSharedPreferences(paraFileName,Context.MODE_PRIVATE);
	loginName  = sharedPref.getString(getString(R.string.login_name_key),"");
	userName  = sharedPref.getString(getString(R.string.user_name_key),"");
	
    }

    private void newMessageNotify()
    {

	NotificationCompat.Builder mBuilder =
	    new NotificationCompat.Builder(this)
	    .setAutoCancel(true)
	    .setSmallIcon(R.drawable.ic_launcher)
	    .setContentTitle(getResources().getString(R.string.notify_title))
	    .setContentText(getResources().getString(R.string.notify_new_message))
	    .setSound(Uri.parse("android.resource://com.yuanma.android.boan/"+ R.raw.ship_bell));
	// Creates an explicit intent for an Activity in your app
	
	PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
								new Intent(this, MessageReadActivity.class), 0);
	mBuilder.setContentIntent(contentIntent);
	NotificationManager mNotificationManager =
	    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
	// mId allows you to update the notification later on.
	int mId=2938;
	mNotificationManager.notify(mId, mBuilder.build());
	
    }
    private void readMessageNotify()
    {
	readHintCount=1;
                    if (Constants.LOGD) {
                        
                        Log.d("JsonPull", String.format("enter readnotiry,reahHintCount: %d",readHintCount));
                    }
	
	NotificationCompat.Builder mBuilder =
	    new NotificationCompat.Builder(this)
	    .setAutoCancel(true)
	    .setSmallIcon(R.drawable.ic_launcher)
	    .setContentTitle(getResources().getString(R.string.notify_title))
	    .setContentText(getResources().getString(R.string.notify_read_message))
	    .setSound(Uri.parse("android.resource://com.yuanma.android.boan/"+ R.raw.bird));
	// Creates an explicit intent for an Activity in your app
	
	PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
								new Intent(this, MessageReadActivity.class), 0);
	mBuilder.setContentIntent(contentIntent);
	NotificationManager mNotificationManager =
	    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
	// mId allows you to update the notification later on.
	int mId=2939;
	mNotificationManager.notify(mId, mBuilder.build());
	
    }

    /**
     * In an IntentService, onHandleIntent is run on a background thread.  As it
     * runs, it broadcasts its current status using the LocalBroadcastManager.
     * @param workIntent The Intent that starts the IntentService. This Intent contains the
     * URL of the web site from which the Json parser gets data.
     */
    @Override
    protected void onHandleIntent(Intent workIntent) {
	running =true;
	
	if(loginName.length()==0) fetchLocalUserInfo();
	
	if(workIntent.hasCategory("After_Login")){
	    max_id=0;
	    msgsToRead.clear();
	    msgsToReview.clear();
	    saveUserInfo();
	    loginName  = LoginActivity.loginName;
	    userName  = LoginActivity.userName;
	    
	}
	if(msgsToReview.size()==0 && msgsToRead.size()==0) max_id=0;
	
	int osize=msgsToRead.size(); //for notify compute
	
	String localUrlString=String.format("http://%s:%s/boan/jsonHintForUser.brl?sgzh=%s&maxid=%d",
						Constants.WEB_SERVER_IP,Constants.WEB_SERVER_PORT,
						loginName,max_id);

        // A URL that's local to this method
        URL localURL;

        try {

            // Convert the incoming data string to a URL.
            localURL = new URL(localUrlString);

            /*
             * Tries to open a connection to the URL. If an IO error occurs, this throws an
             * IOException
             */
            URLConnection localURLConnection = localURL.openConnection();

            // If the connection is an HTTP connection, continue
            if ((localURLConnection instanceof HttpURLConnection)) {

                // Broadcasts an Intent indicating that processing has started.
                if(appRunning) mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_STARTED);

                // Casts the connection to a HTTP connection
                HttpURLConnection localHttpURLConnection = (HttpURLConnection) localURLConnection;

                // Sets the user agent for this request.
                localHttpURLConnection.setRequestProperty("User-Agent", Constants.USER_AGENT);


                // Reports that the service is about to connect to the RSS feed
                if(appRunning) mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_CONNECTING);

                // Gets a response code from the RSS server
                int responseCode = localHttpURLConnection.getResponseCode();

                switch (responseCode) {

                    // If the response is OK
		case HttpURLConnection.HTTP_OK:

		    // Gets the last modified data for the URL
		    long lastModifiedDate = localHttpURLConnection.getLastModified();


		    String jsnString= Utility.fromStream(localURLConnection.getInputStream());
		    JSONTokener jsonParser = new JSONTokener(jsnString);
		    JSONArray msgObjects= (JSONArray)jsonParser.nextValue();
		    for(int i=0;i<msgObjects.length();i++){ 
                        JSONObject msgObj = (JSONObject)msgObjects.opt(i); 
                        Message msg = new Message(msgObj.getInt("app_msg_id"),
						  msgObj.getBoolean("has_read"),
						  msgObj.getString("app_msgTitle"),
						  msgObj.getString("app_msgContent"));
			if(msg.msg_id>max_id) max_id=msg.msg_id;
			if(msg.has_read)
			    msgsToReview.add(msg);
			else
			    msgsToRead.add(msg);
			

		    }
			 
		    break;

                }

                // Reports that the feed retrieval is complete.
                if(appRunning) mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_COMPLETE);
		if(appRunning && workIntent.hasCategory("After_Login"))
		    mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_READ);

            }

	    // Handles possible exceptions
        } catch (MalformedURLException localMalformedURLException) {

            localMalformedURLException.printStackTrace();

        } catch (IOException localIOException) {

            localIOException.printStackTrace();

        } catch (JSONException localJsonException) {

            localJsonException.printStackTrace();

	} catch (ClassCastException localCastException) {
            localCastException.printStackTrace();

        } finally {

            // If an exception occurred, close the cursor to prevent memory leaks.
	    running=false;
	    
	    
        }
                    if (Constants.LOGD) {
                        
                        Log.d("JsonPull", String.format("max_id: %d. msgSize:%d. osize:%d",max_id,msgsToRead.size(),osize));
                    }
	if(msgsToRead.size()>osize) newMessageNotify();
	else if(readHintCount<=0 && msgsToRead.size()>0) readMessageNotify();
	else readHintCount--;

	
	AlarmReceiver.completeWakefulIntent(workIntent);
	running = false;
	
    }

}
